package com.flnet.web.controller.treasure;

import com.flnet.common.base.AjaxResult;
import com.flnet.common.utils.file.FileUtils;
import com.flnet.framework.web.base.BaseController;
import com.flnet.system.domain.BootdoConfig;
import com.flnet.system.domain.FileDO;
import com.flnet.system.domain.FileType;
import com.flnet.system.domain.PhotoResult;
import com.flnet.treasure.domain.FileRef;
import com.flnet.treasure.domain.Result;
import com.flnet.treasure.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("/common/sysFile")
public class FileController extends BaseController {

    @Autowired
    private BootdoConfig bootdoConfig;

    @Autowired
    CommonService commonService;

    @ResponseBody
    @PostMapping("/upload1")
    AjaxResult upload1(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if ("test".equals(getLoginName())) {
            return AjaxResult.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        String fileName = file.getOriginalFilename();
        fileName = FileUtils.RenameToUUID(fileName);
        FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
        try {
            FileUtils.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return AjaxResult.error();
        }
        PhotoResult result = new PhotoResult();
        result.setUrl(fileName);
        return AjaxResult.success().put("url",bootdoConfig.getUploadPath()+fileName);
    }
    @ResponseBody
    @PostMapping("/upload")
    Result upload(MultipartFile file){
        Result result = Result.returnFailure();
        try {
            FileRef fileRef = commonService.uploadImg(file,bootdoConfig.getUploadPath(),bootdoConfig.getUploadPath());
            result = Result.returnSuccess();
            result.setObject(fileRef);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
    }
}
